package myself.util;
/**
 * 
 * 页面跳转util
 * 
 * */
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;

public class ApiController {

	public static final Charset DEFAULT_CHARSET = Charset.forName("utf-8");
	private static final Logger log = LoggerFactory.getLogger(ApiController.class);

	@RequestMapping(value = "/api.htm")
	public ModelAndView api(HttpServletRequest request) throws IOException {
		String cookie = request.getQueryString().substring(
				request.getQueryString().indexOf("=") + 1);
		String requestBody = StreamUtils.copyToString(request.getInputStream(),
				DEFAULT_CHARSET);
		log.info("request body: " + requestBody);
		Map<String, Object> map = JSON.parseObject(requestBody);
		Set<String> set = map.keySet();
		Iterator<String> it = set.iterator();
		while (it.hasNext()) {
			String key = it.next();
			if (map.get(key).equals("")) {
				it.remove();
			}
		}
		map.put("cookie", cookie);
		return new ModelAndView("forward:/" + map.get("action") + ".htm", map);
	}

	@RequestMapping(value = "/apiv2.htm")
	public ModelAndView apiv2(HttpServletRequest request) throws IOException {
		String cookie = request.getQueryString().substring(
				request.getQueryString().indexOf("=") + 1);
		String requestBody = StreamUtils.copyToString(request.getInputStream(),
				DEFAULT_CHARSET);
		log.info("request body: " + requestBody);
		Map<String, Object> map = JSON.parseObject(requestBody);
		map.put("cookie", cookie);
		return new ModelAndView("forward:/" + map.get("action") + ".htm", map);
	}
}
